package com.gjy.quartz.cluster;

import com.alibaba.druid.pool.DruidDataSource;
import org.quartz.utils.PoolingConnectionProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * org.quartz.dataSource.druid.connectionProvider.class=com.gjy.quartz.cluster.DruidConnectionProvider
 */
public class DruidConnectionProvider implements PoolingConnectionProvider {
    private static final Logger log = LoggerFactory.getLogger(DruidConnectionProvider.class);

    public static final String POOLING_PROVIDER_NAME = "druid";
    private DruidDataSource dataSource;

    public DruidConnectionProvider() {
        try {
            this.dataSource = new DruidDataSource();
            dataSource.setUrl("jdbc:mysql://localhost:3306/quartz");
            dataSource.setUsername("root");
            dataSource.setPassword("Oracle@12");
            dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
            dataSource.init();
            log.info("druid数据源初始化成功");
        } catch (Exception e) {
            log.error("classpath下没有quartz.properties,使用默认设置");
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        return this.dataSource.getConnection();
    }

    @Override
    public void shutdown() throws SQLException {
        if (!dataSource.isClosed()) {
            this.dataSource.close();
        }
    }

    @Override
    public void initialize() throws SQLException {

    }

    @Override
    public DataSource getDataSource() {
        return this.dataSource;
    }
}
